_ = require 'underscore'
async =  require 'async'

DepartmentModel = require './department_model'
PageUtils =  require '../utils/page_util'

DepartmentServ = 

  # 获取查询条件
  getQuery: (params) ->
    tmp = {}
    # 查询条件
    query = params?.query
    # 是否有查询属性
    if not query
      return tmp 

    # 遍历查询条件
    for key, value of query
      if '' isnt value
        tmp[key] = value
    return tmp

  # 保存/修改单个
  save: (obj, cbf) ->
    if not obj or _.isEmpty obj
      return cbf '保存的记录不能为空！', null
    # 新建临时Model
    tmpModel = new DepartmentModel obj
    # 查询单个条件
    query = {_id : obj._id}
    # 查询单条记录
    DepartmentModel.find query, (err, res) ->
      if err
        return cbf err, null
      # 不存在，执行创建
      if 0 is res?.length
        tmpModel.save cbf
      # 存在，执行更新
      else
        DepartmentModel.findOneAndUpdate query, {$set: obj}, cbf

  # 删除
  remove: (params, cbf) ->
    if not params or _.isEmpty params
      return cbf '删除条件不能为空！', null
    DepartmentModel.remove params, (error, result) ->
      if error
        return cbf "删除记录失败！#{error}", null
      if '0' is '' + result
        return cbf "删除的记录不存在！", null
      return cbf null, {status: 'success', error: ''}

  # 查询 - 分页
  # query 查询条件 {field_name: 'value'}
  # params 排序、分页条件
  # {query: {field_name: 'value'}, sorts: {field_name: 1}, pageNum: 1, pageSize: 10}
  query: (params, cbf) ->
    query = DepartmentServ.getQuery params
    # 排序条件初始值
    if not params?.sorts
      params.sorts = {}
    # 默认按时间倒序
    params.sorts.updated_at = -1
    return PageUtils.pageQuery DepartmentModel, query, params?.sorts, params?.pageSize, params?.pageNum, cbf

  # 查询 - 不分页
  find: (params, cbf) ->
    if not params or _.isEmpty params
      return cbf '查询条件不能为空！', null
    DepartmentModel.find params, (error, result) ->
      if error
        return cbf "查询记录失败！#{error}", null
      if 0 is result?.length
        return cbf "查询的记录不存在！", null
      return cbf null, result

  # 批量保存/更新多个
  batSaveDepartment: (departmentArr, cbf) ->
    # 并行执行函数数组
    funcs = _.map departmentArr, (department) ->
      (cb) ->
        DepartmentServ.save department, cb
    # 并行执行
    return async.parallel funcs, cbf

module.exports = DepartmentServ